package com.suke.czx.modules.tb.controller;

import java.util.*;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.suke.czx.modules.tb.entity.TbProduct;
import com.suke.czx.modules.tb.service.TbProductService;
import com.suke.czx.modules.tb.vo.MessageHeadVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.suke.czx.modules.tb.entity.TbMessage;
import com.suke.czx.modules.tb.service.TbMessageService;
import com.suke.czx.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;

import javax.annotation.Resource;

/**
 * 用户消息私信表
 *
 * @author developer
 * @email developer@163.com
 * @date 2025-05-20 18:48:09
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tb/message")
@Api(value = "TbMessageController", tags = "用户消息私信表")
public class TbMessageController extends AbstractController {
    private final TbMessageService tbMessageService;

    @Resource
    private TbProductService tbProductService;

    // 获取消息列表
    @ApiOperation(value = "获取对话消息列表")
    @PostMapping("/getMessageHeadList")
    public R getMessageList(@RequestBody Map<String,Object> params) {
        String userId = getUserId();
        List<MessageHeadVO> list = tbMessageService.getMessageHeadList(userId, params);
        return R.ok().setData(list);
    }

    // 发送消息
    @ApiOperation(value = "发送消息")
    @PostMapping("/sendMessage")
    public R sendMessage(@RequestBody TbMessage tbMessage) {
        if(StringUtils.isBlank(getUserId()) || StringUtils.isBlank(tbMessage.getContent()) || null == tbMessage.getProductId() || 0L == tbMessage.getProductId()){
            return R.error("参数错误");
        }
        TbProduct product = tbProductService.getById(tbMessage.getProductId());
        if(product == null){
            return R.error("参数错误");
        }
        Date date = new Date();
        String userId = getUserId();
        // 判断是否有历史消息
        boolean flag = tbMessageService.setDeafultHeadMessage(product.getId(), userId, product.getUserId(), date);
        if(!flag){
            return R.error("操作，请联系管理员");
        }
        tbMessage.setSenderId(getUserId());
        if (StringUtils.isBlank(tbMessage.getReceiverId())) {
            tbMessage.setReceiverId(product.getUserId());
        }
        tbMessage.setIsRead(0);
        tbMessage.setContentType("message");
        tbMessage.setCreateDate(new Date(System.currentTimeMillis()));
        tbMessageService.save(tbMessage);
        return R.ok();
    }

    // 接受我的最新消息
    @ApiOperation(value = "获取我的最新消息")
    @PostMapping("/getMyNewestMessage")
    public R getMyNewestMessage(@RequestBody Map<String,Object> params) {
        Integer productId = (Integer) params.get("productId");
        if(StringUtils.isBlank(getUserId()) || null == productId || 0L == productId){
            return R.error("参数错误");
        }
        LambdaQueryWrapper<TbMessage> tmlqw = new LambdaQueryWrapper<>();
        tmlqw.orderByAsc(TbMessage::getCreateDate);
        tmlqw.ne(TbMessage::getContentType,"head");
        tmlqw.eq(TbMessage::getProductId, productId);
        tmlqw.eq(TbMessage::getReceiverId, getUserId());
        tmlqw.eq(TbMessage::getIsRead, 0);
        List<TbMessage> list = tbMessageService.list(tmlqw);
        // 将查到的数据 的 isRead 修改为 1
        if(CollectionUtils.isNotEmpty(list)){
            for (TbMessage tbMessage1 : list) {
                tbMessage1.setIsRead(1);
            }
            tbMessageService.updateBatchById(list);
        }
        return R.ok().setData(list);
    }

    // 分页获取历史已读消息
    @ApiOperation(value = "分页获取历史已读消息")
    @PostMapping("/getMyHistoryReadMessage")
    public R getMyHistoryReadMessage(@RequestBody Map<String,Object> params) {
        Integer productId = (Integer) params.get("productId");
        if(StringUtils.isBlank(getUserId()) || null == productId || 0L == productId){
            return R.error("参数错误");
        }
        LambdaQueryWrapper<TbMessage> tmlqw = new LambdaQueryWrapper<>();
        tmlqw.orderByAsc(TbMessage::getCreateDate);
        tmlqw.ne(TbMessage::getContentType,"head");
        tmlqw.eq(TbMessage::getProductId, productId);
        // receiverId或 senderId是自己
        tmlqw.and(and1-> and1.and(q -> q.eq(TbMessage::getReceiverId, getUserId()))
        .or(q -> q.eq(TbMessage::getSenderId, getUserId())));
        IPage<TbMessage> listPage = tbMessageService.page(mpPageConvert.pageParamConvert(params), tmlqw);
        // 将查到的数据 的 isRead 修改为 1
        List<TbMessage> updateList = new ArrayList<>();
        if(null != listPage && CollectionUtils.isNotEmpty(listPage.getRecords())){
            for (TbMessage tbMessage1 : listPage.getRecords()) {
                if(0 == tbMessage1.getIsRead() && Objects.equals(tbMessage1.getReceiverId(), getUserId())){
                    tbMessage1.setIsRead(1);
                    updateList.add(tbMessage1);
                }
            }
        }
        if(CollectionUtils.isNotEmpty(updateList)){
            tbMessageService.updateBatchById(updateList);
        }
        return R.ok().setData(listPage);
    }

    /**
     * 列表
     */
    @ApiOperation(value = "用户消息私信表列表")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        QueryWrapper<TbMessage> queryWrapper = new QueryWrapper<>();
        final String keyword = mpPageConvert.getKeyword(params);
        if (StrUtil.isNotEmpty(keyword)) {

        }
        IPage<TbMessage> listPage = tbMessageService.page(mpPageConvert.<TbMessage>pageParamConvert(params), queryWrapper);
        return R.ok().setData(listPage);
    }


    /**
     * 新增用户消息私信表
     */
    @ApiOperation(value = "新增用户消息私信表数据")
    @SysLog("新增用户消息私信表数据")
        @PostMapping()
        public R save(@RequestBody TbMessage tbMessage) {
        tbMessageService.save(tbMessage);
        return R.ok();
    }


    /**
     * 修改
     */
    @ApiOperation(value = "修改用户消息私信表数据")
    @SysLog("修改用户消息私信表数据")
        @PutMapping()
        public R update(@RequestBody TbMessage tbMessage) {
        tbMessageService.updateById(tbMessage);
        return R.ok();
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除用户消息私信表数据")
    @SysLog("删除用户消息私信表数据")
        @DeleteMapping()
        public R delete(@RequestBody TbMessage tbMessage) {
        tbMessageService.removeById(tbMessage.getId());
        return R.ok();
    }

}
